package com.example.bpmn.service;

import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.RuntimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.kafka.annotation.KafkaListener;
import com.example.bpmn.event.ProcessEvent;
import com.example.bpmn.service.ProcessCallbackService;
import com.example.bpmn.service.ProcessEventPublisher;
import lombok.RequiredArgsConstructor;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class ProcessEventHandler {

    private final ProcessCallbackService callbackService;
    private final ProcessEventPublisher eventPublisher;

    public void handleProcessEvent(ProcessEvent event) {
        try {
            log.info("处理流程事件: {}", event);
            
            // 1. 更新流程状态
            updateProcessStatus(event);
            
            // 2. 发送回调通知
            notifyBusinessSystem(event);
            
            // 3. 触发后续动作
            triggerNextAction(event);
            
        } catch (Exception e) {
            log.error("处理流程事件失败: {}", e.getMessage(), e);
            handleEventError(event, e);
        }
    }

    private void updateProcessStatus(ProcessEvent event) {
        // 根据事件更新流程状态
    }

    private void notifyBusinessSystem(ProcessEvent event) {
        // 发送回调通知
        callbackService.sendCallback(event);
    }

    private void triggerNextAction(ProcessEvent event) {
        // 触发后续流程
    }

    private void handleEventError(ProcessEvent event, Exception e) {
        // 处理错误情况
        callbackService.sendErrorCallback(
            event.getBusinessKey(),
            "EVENT_HANDLE_ERROR",
            e.getMessage()
        );
    }
} 